package com.tunnel.home.server;

import org.axe.annotation.ioc.Autowired;
import org.axe.annotation.ioc.Service;
import org.axe.util.MD5Util;
import org.eclipse.jetty.util.StringUtil;

import com.tunnel.home.common.Constant;
import com.tunnel.home.common.RedisUtil;
import com.tunnel.home.dao.UserDao;
import com.tunnel.home.entity.User;

@Service
public class UserService {

	@Autowired
	private UserDao userDao;
	
	public User checkUserAuth(String email,String password) throws Exception{
		User user = userDao.getUser(email);
		if(user == null){
			throw new Exception("账号或密码错误");
		}
		password = MD5Util.getMD5Code(password+user.getSalt());
		if(!password.equals(user.getPassword())){
			//如果用户是验证了忘记密码，需要重置，那就更新密码
			String isRest = RedisUtil.getAndDelString(Constant.RESET_PASSWORD+user.getId());
			if(StringUtil.isNotBlank(isRest)){
				//说明是需要重置密码
				//那么后续的邮箱也就自动激活了，因为点过重置密码的验证邮件也就可以了
				userDao.resetPassword(user.getId(), password);
				user.setEmailStatus(1);
			}else{
				throw new Exception("账号或密码错误");
			}
			
		}
		
		if(user.getEmailStatus() == 0){
			throw new Exception("账号未激活，请前往邮箱完成账号激活");
		}
		
		return user;
	}
	
}
